﻿/*
 * Nicolás Lareu.
 * Sebastián A. Endler.   
  MIT Licensed
  Some portions of the code are based on Mootools 1.24 http://mootools.net
*/

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

(function () {
    function _PrivateParameters(options) {
        try {
            this.URL = '../../../DALService.svc/CallProcedure'; //as default
            this.Procedure = '';
            if (options) for (var option in options) eval('this.' + option + '=options["' + option + '"]');
            if (this.events) {
                this.events.onError = (this.events.onError) || (function (error) { });
                this.events.onFailure = (this.events.onFailure) || (function (message) { });
                this.events.onComplete = (this.events.onComplete) || (function () { });
                this.events.onChange = (this.events.onChange) || (function () { });
            } else {
                this.events = {};
                this.events.onError = function (error) { };
                this.events.onFailure = function (message) { };
                this.events.onComplete = function () { };
                this.events.onChange = function () { };
            }
            this.version = new Object();
            this.version.Namespace = 'IndustrialDashboard';
            this.version.Class = '';
            this.version.info = 'ID 2.0';
            return this;
        } catch (Error) { }
    }
    window.PrivateParameters = function (options) { return new _PrivateParameters(options); }
})();

(function () {
    function _PrivateClasses(options) {
        try {
            for (var opt in options) this[opt] = options[opt]();
            return this;
        } catch (Error) { window.status = Error.message; return null; }
    }
    window.PrivateClasses = function (options) { return new _PrivateClasses(options); };
})();

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

var specialChars = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }

function replaceChars(chr) {
    return specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
}

function getType(obj) {
    try {
        if (obj == undefined) return false;
        if (obj.nodeName) {
            switch (obj.nodeType) {
                case 1: return 'element';
                case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
            }
        } else if (typeof obj.length == 'number') {
            if (obj.callee) return 'arguments';
            else if (obj.item) return 'collection';
            else if (typeof (obj) != 'string') return 'array';
        }
        if (typeof (obj)) return (typeof (obj) == 'number' && !isFinite(obj)) ? false : typeof (obj);
        return typeof obj;
    } catch (Error) { }
}

function JSONEncode(obj){
    try{
        switch (getType(obj)){
			case 'string':
				return '"' + obj.replace(/[\x00-\x1f\\"]/g, replaceChars) + '"';
			case 'array':    				
                var parse = '[';
                for(var i=0;i<obj.length;i++) parse += String(JSONEncode(obj[i]))+',';
                parse = (parse.length>1)?parse.substring(0,parse.length-1):parse;
                return (parse +']');
			case 'object': 
				var string = [];
                for(var key in obj){
                    var json = JSONEncode(obj[key]);
                    if (json) string.push(JSONEncode(key)+':'+json);
                }
				return '{' + string + '}';
			case 'number': 
            case 'boolean': 
                return String(obj);
			case false: 
                return 'null';
		}
	    return null;
    }catch(Error){return Error;}
}

function generateHtmlPage(strHtml) {
        var header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd\">"; 

        header += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>"; 
        for(i = 0; i < document.styleSheets.length; i++) 
        {
            header += "<link href=\"" + document.styleSheets[i].href; 

            header += "\" rel=\"stylesheet\" type=\"text/css\" media =\"screen\"/>"; 
        }
        header += "</head>"; 
        strHtml = header + "<body>"+ strHtml + "</body></html>"; 
        
        return formatToSendingHTML(strHtml); 
}

function formatToSendingHTML(strHtml) {
    /*
    Replaces in the html code some characters, leaving the string in only one line,
    with the < replaced to a left pointing arrow (\u2190) and > replaced to the right
    pointing arrow (\u2192). This values are needed to then convert the string into
    html - readeble code.
    003C -> 2190
    003E -> 2192
    0022 -> \\\"
    \n -> ""
    \r -> ""
    &%13 -> ""
    &%10 -> ""
    */

    var r = /\u0022/g; 
    r = /\n/g;
    strHtml = strHtml.replace(r,""); 
    r = /\r/g;
    strHtml = strHtml.replace(r,""); 
    r = /\u003C/g;
    strHtml = strHtml.replace(r,"\u2190"); 
    r = /\u003E/g;
    strHtml = strHtml.replace(r,"\u2192"); 
    r = /&#10;|&#13;/g;
    strHtml = strHtml.replace(r,""); 
    return strHtml;
}

function getHtmlString(strhtml, height)//This should be called from the html pages to generate the object to send.
{
    return generateHtmlPage(strhtml);
}

//////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////// 

(function ()
{
    /* Author: Nicolás Lareu. */
    try
    {
        function _DestinationPDF(options)
        {
            try
            {
                var widgetsList = new Array();
                var privateParameters = {
                    docAttributes:{
                        fileName:null
                        ,marginTop:null
                        ,marginLeft:null
                        ,marginBottom:null
                        ,marginRight:null
                    }
                    ,events:{
                        onError:function(){}
                    }
                };

                function _initialize(options)
                {
                    try
                    {
                        widgetsList = new Array();

                        privateParameters = new PrivateParameters(options);
                        privateParameters.docAttributes = privateParameters.docAttributes || new Object();
                        privateParameters.docAttributes.fileName = ((privateParameters.docAttributes.fileName)&&(privateParameters.docAttributes.fileName!=''))
                                                                    ? ((privateParameters.docAttributes.fileName.match('.*(\.pdf)'))
                                                                        ? privateParameters.docAttributes.fileName
                                                                        : privateParameters.docAttributes.fileName + '.pdf'
                                                                        )
                                                                    : null;
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                }

                /*-----------------------------------------------------------------------*/
                /*------------------------------Instance it------------------------------*/
                /*-----------------------------------------------------------------------*/
                _initialize(options);
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/

                function _addPdfWidget(pdfWidget){
                    try {
                        if(pdfWidget) widgetsList.push(pdfWidget.getWidgetData());
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                }

                function _sendData(){
                    try {
                        var form = document.createElement('form');
                        form.action = privateParameters.URL;
                        form.method = 'post';
                        form.style.display = 'none';
                        document.documentElement.appendChild(form);

                        var inputHidden = document.createElement('input');
                        inputHidden.type = 'hidden';
                        inputHidden.name = 'destinationPdfValue';
                        inputHidden.value = JSONEncode({ Widgets:widgetsList, DocAttributes:privateParameters.docAttributes});
                        form.appendChild(inputHidden);
                                                
                        form.submit();
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                }

                /*----------------*/
                /*-----Public-----*/
                /*----------------*/

                /*----------------------*/
                /*--------Methods-------*/
                /*----------------------*/
                this.addPdfWidget=function(pdfWidget){
                    _addPdfWidget(pdfWidget);
                }
                this.sendData=function(){
                    _sendData();
                }
            }
            catch(Error){window.status=Error.Message;}
        }

        window.DestinationPDF = function(instanceOption){ return new _DestinationPDF(instanceOption);};
    }
    catch(Error){window.status=Error.Message}
})();

(function(){
    try {
        function _PdfWidget(options){
            try {
                var content;
                var privateParameters={
                    type:null
                    ,attributes:{
                        width:null
                        ,height:null
                    }
                    ,events:{
                        onError:function(){}
                    }
                };

                function _initialize(options){
                    try {
                        content = null;

                        privateParameters = new PrivateParameters(options);
                        privateParameters.type = privateParameters.type || 3;
                        privateParameters.attributes = privateParameters.attributes || new Object();
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                }

                /*-----------------------------------------------------------------------*/
                /*------------------------------Instance it------------------------------*/
                /*-----------------------------------------------------------------------*/
                _initialize(options);
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/

                function _setContent(newContent){
                    try {
                        if(!newContent)    throw new Error({message:"The \"Content\" can not be null."});                        
                        content = newContent;
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                }

                function _getWidgetData(){
                    var data = new Object();
                    try {
                        data.Type = privateParameters.type;
                        data.WidgetData = JSONEncode(content);
                        data.Attributes = privateParameters.attributes;
                        return data;
                    }
                    catch (Error) {privateParameters.events.onError(Error);}
                    return null;
                }

                /*----------------*/
                /*-----Public-----*/
                /*----------------*/

                /*----------------------*/
                /*--------Methods-------*/
                /*----------------------*/
                this.setContent=function(newContent){
                    _setContent(newContent);
                }
                this.getWidgetData=function(){
                    return _getWidgetData();
                }
            }
            catch (Error) { window.status = Error.Message; }
        }

        window.PdfWidget = function(instanceOptions){return new _PdfWidget(instanceOptions);};
    }
    catch (Error) { window.status = Error.Message; }    
})();